package com.tool.emulator.apple2;

import com.tool.emulator.common.IODevice;
import com.tool.emulator.common.VirtualDevice;

/**
 * Keyboard.java @author tl 2011-6-19
 */
public class Keyboard extends VirtualDevice implements IODevice {
	protected final Apple2 apple2;
	protected transient volatile KeyboardUI ui;
	private volatile int current_input = 0;

	public Keyboard(Apple2 apple2) {
		super("Keyboard");
		this.apple2 = apple2;
		this.setDefaultUI();
		apple2.BUS.initIO(Apple2.ADDR_KEY_IN, 1, this);
		apple2.BUS.initIO(Apple2.ADDR_KEY_RESET, 1, this);
		apple2.BUS.initRom(0xC061, 0, 0, 0);
	}

	public int read_io(int addr) {
		if (addr == Apple2.ADDR_KEY_IN) {
			int v = this.current_input & 0xff;
			return v;
		}
		if (addr == Apple2.ADDR_KEY_RESET)
			return this.resetInput();
		return 0;
	}

	private int resetInput() {
		int val = this.current_input &= 0x7F;
		return val;
	}

	public boolean canInput() {
		return this.current_input < 128;
	}

	public void setInput(int code) {
		if (!Apple2.APPLEIIE) {
			if (code >= 'a' && code <= 'z') code = code + 'A' - 'a';
		}
		//System.err.println("input code is " + Integer.toHexString(code) + "\t" + (char)code);
		this.current_input = (code & 0xff) | 0x80;
	}

	public void write_io(int addr, int val) {
		if (addr == Apple2.ADDR_KEY_RESET)
			this.resetInput();
	}

	public synchronized void setUI(KeyboardUI ui) {
		if (this.ui != null)
			this.ui.uninstall(this);
		this.ui = ui;
		if (ui != null)
			ui.install(this);
	}

	public KeyboardUI setDefaultUI() {
		KeyboardUI ui = (KeyboardUI) apple2.MONITOR.getUI();
		this.setUI(ui);
		return ui;
	}

}
